package cn.kgc.ubagnet.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;
import java.net.PasswordAuthentication;

@EnableWebSecurity
public class MySecutityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    UserDetailsService userDetailsService;

//    安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()//对请求进行授权
        .antMatchers(
//           "/css/**",
//            "/fonts/**",
//            "/images/**",
//            "/js/**",
//            "/temp_article/**",
//            "/xtiper/**",
//             "/webjars/**",
//             "/",
//             "/seleProtype",
//             "/seleProduct",
//             "/seleProducttext",
//             "/pro/query/by/id",
//             "/pro/for/id",
//             "/proimg/query/by/id",
//              "/pro/for/id",
//               "/item_show"
                "/udai_welcome.html",
                "/udai_order.html",
                "/udai_integral.html",
                "/udai_shopcart.html",
                "/udai_collection.html",
                "/r-item-hd",
                "/toYonghu" //用户中心页面权限
        )//使用NAT风格设置要授权的URL
        //.permitAll()//允许上面使用NAT风格设置的全部请求
        //.anyRequest()//其他未设置的全部请求需要认证
         .authenticated()//需要认证
        .and()
        .formLogin()//设置未授权请求跳转到登录页面
        .loginPage("/tologin")//指定登陆页面
        .permitAll()
        .loginProcessingUrl("/security/dologin")
        .usernameParameter("loginAcct")//指定页面参数
        .passwordParameter("userPswd")
        .defaultSuccessUrl("/")//登录成功跳转地址
        .failureUrl("/tologin?error=true")//登录失败跳转URL，并传参方便前端进行判断
        .and()
        .logout()
        .logoutUrl("/security/logout")
        .logoutSuccessUrl("/")
        .and()
        .csrf()
        .disable()
        .rememberMe().rememberMeParameter("remember")
        ;

    }

//    授权


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
